import { ref } from 'vue';
import { apiService } from '@/services/api-service';
import { ElMessage } from 'element-plus';

export function useImageUpload() {
  const uploading = ref(false);
  const deleting = ref(false);
  const uploadError = ref<string | null>(null);

  const uploadImage = async (file: File): Promise<{ url: string; filename: string } | null> => {
    // 验证文件类型
    if (!file.type.includes('image/')) {
      ElMessage.error('只能上传图片文件!');
      return null;
    }

    // 验证文件大小 (限制为5MB)
    if (file.size / 1024 / 1024 > 5) {
      ElMessage.error('图片大小不能超过5MB!');
      return null;
    }

    uploading.value = true;
    uploadError.value = null;

    try {
      const response = await apiService.uploadImage(file);

      if (response.success && response.data) {
        ElMessage.success('图片上传成功!');
        return response.data;
      } else {
        uploadError.value = response.error || response.message || '上传失败';
        ElMessage.error(uploadError.value);
        return null;
      }
    } catch (error: any) {
      uploadError.value = error.message || '网络错误';
      ElMessage.error(uploadError.value);
      return null;
    } finally {
      uploading.value = false;
    }
  };

  const deleteImage = async (filename: string): Promise<boolean> => {
    deleting.value = true;
    uploadError.value = null;

    try {
      const response = await apiService.deleteImage(filename);

      if (response.success) {
        ElMessage.success('图片删除成功!');
        return true;
      } else {
        uploadError.value = response.error || response.message || '删除失败';
        ElMessage.error(uploadError.value);
        return false;
      }
    } catch (error: any) {
      uploadError.value = error.message || '网络错误';
      ElMessage.error(uploadError.value);
      return false;
    } finally {
      deleting.value = false;
    }
  };

  const getImageUrl = (filename: string): string => {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
    return `${baseUrl}/images/${filename}`;
  };

  return {
    uploading,
    deleting,
    uploadError,
    uploadImage,
    deleteImage,
    getImageUrl
  };
}
